package com.example.activitytest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class SecondActivity extends AppCompatActivity {

    private static final String TAG = "SecondActivity";
    public static final int RESPONSE_TO_FIRSTACTIVITY = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        //接收FirstActivity传来的数据
//        Intent intent = getIntent();
//        String dataFromFirstActivity = intent.getStringExtra("extra_data");
//        Log.d(TAG, dataFromFirstActivity);

        //返回数据给FirstActivity
        Button button2 = (Button) findViewById(R.id.button_2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "button2");
                Intent intent = new Intent();
                intent.putExtra("data_return","Hello  FirstActivity");
                setResult(RESPONSE_TO_FIRSTACTIVITY, intent);
                // 此活动销毁后会返回上一活动，且上一活动会调用onActivityResult()
                finish();
            }
        });
    }

    //按Back键时，返回数据给FirstActivity
    @Override
    public void onBackPressed() {
        Intent intent =new Intent();
        intent.putExtra("data_return", "Hello  FirstActivity");
        setResult(RESPONSE_TO_FIRSTACTIVITY, intent);
        finish();
    }
}